import os
import sys
import webbrowser
from threading import Timer
from app import app

def open_browser():
    webbrowser.open('http://127.0.0.1:5001')

if __name__ == '__main__':
    # Determine if application is a script file or frozen exe
    if getattr(sys, 'frozen', False):
        # If the application is run as a bundle, the PyInstaller bootloader
        # extends the sys module by a flag frozen=True and sets the app 
        # path into variable _MEIPASS'.
        application_path = sys._MEIPASS
    else:
        application_path = os.path.dirname(os.path.abspath(__file__))

    # Change working directory to application path
    os.chdir(application_path)
    
    # Ensure data directory exists
    os.makedirs('data', exist_ok=True)
    
    # Open browser after a short delay
    Timer(1.5, open_browser).start()
    
    # Start Flask application
    app.run(debug=False, port=5001)
